package com.wanxi.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.wanxi.dto.AliPayDTO;
import com.wanxi.dto.OrderDTO;
import com.wanxi.dto.OrderDetailsDTO;
import com.wanxi.entity.Order;
import com.wanxi.entity.OrderDetails;
import com.wanxi.feign.OrderClient;
import com.wanxi.mapper.OrderMapper;
import com.wanxi.query.OrderDetailsQuery;
import com.wanxi.query.OrderQuery;
import com.wanxi.result.CommonResult;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(description = "订单服务")
@RestController
@RequestMapping("/order")
@Service
public class OrderServiceImpl implements OrderClient {

    @Resource
    private OrderMapper orderMapper;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    @PostMapping("/addOrder")
    public CommonResult<?> addOrder(@RequestBody OrderDTO orderDTO) {
        logger.info("[添加订单的输入参数是(用户id:{}},订单金额:{},订单编号:{},订单状态:{})]", orderDTO.getUserId(), orderDTO.getOrderAmount(), orderDTO.getOrderNumber(), orderDTO.getOrderState());
        Integer i = orderMapper.addOrder(orderDTO);
        if (i > 0) {
            logger.info("[添加订单的操作成功,出参是:{}]", i);
            return CommonResult.success("添加订单成功");
        } else {
            return CommonResult.failed("添加订单失败");
        }
    }

    @Override
    @PutMapping("/deleteOrder")
    public CommonResult<?> deleteOrder(@RequestBody OrderDTO orderDTO) {
        logger.info("[删除订单的输入参数是({})]", orderDTO);
        Integer i = orderMapper.deleteOrder(orderDTO);
        if (i > 0) {
            logger.info("[删除订单的输出参数是({})]", i);
            return CommonResult.success("删除订单成功");
        } else {
            logger.info("[删除订单的输出参数是({})]", i);
            return CommonResult.failed("删除订单失败");
        }
    }

    @Override
    @PutMapping("/updateOrder")
    public CommonResult<?> updateOrder(@RequestBody OrderDTO orderDTO) {
        logger.info("[修改订单的输入参数是({})]", orderDTO);
        Integer i = orderMapper.updateOrder(orderDTO);
        if (i > 0) {
            logger.info("[修改订单的输出参数是({})]", i);
            return CommonResult.success("修改订单状态成功");
        } else {
            logger.info("[修改订单的输出参数是({})]", i);
            return CommonResult.failed("修改订单状态失败");
        }
    }

    @Override
    @GetMapping("/findOrder")
    public CommonResult<?> findOrder(OrderQuery orderQuery) {
        logger.info("[查询订单的输入参数是({})]", orderQuery);
        List<Order> orderList = orderMapper.findOrder(orderQuery);
        logger.info("[查询订单的输出参数是({})]", orderList);
        return CommonResult.success(orderList, "查询订单信息成功");
    }


    @Override
    @PostMapping("/addOrderDetails")
    public CommonResult<?> addOrderDetails(@RequestBody OrderDetailsDTO orderDetailsDTO) {
        logger.info("[添加订单详情的输入参数是({})]", orderDetailsDTO);
        Integer i = orderMapper.addOrderDetails(orderDetailsDTO);
        if (i > 0) {
            logger.info("[添加订单详情的输出参数是({})]", i);
            return CommonResult.success("添加订单详情成功");
        } else {
            logger.info("[添加订单详情的输出参数是({})]", i);
            return CommonResult.failed("添加订单详情失败");
        }
    }

    @Override
    @PutMapping("/deleteOrderDetails")
    public CommonResult<?> deleteOrderDetails(@RequestBody OrderDetailsDTO orderDetailsDTO) {
        logger.info("[删除订单详情的输入参数是({})]", orderDetailsDTO);
        Integer i = orderMapper.deleteOrderDetails(orderDetailsDTO);
        if (i > 0) {
            logger.info("[删除订单详情的输出参数是({})]", i);
            return CommonResult.success("删除订单详情成功");
        } else {
            logger.info("[删除订单详情的输出参数是({})]", i);
            return CommonResult.failed("删除订单详情失败");
        }
    }

    @Override
    @PutMapping("/updateOrderDetails")
    public CommonResult<?> updateOrderDetails(@RequestBody OrderDetailsDTO orderDetailsDTO) {
        logger.info("[修改订单详情的输入参数是({})]", orderDetailsDTO);
        Integer i = orderMapper.updateOrderDetails(orderDetailsDTO);
        if (i > 0) {
            logger.info("[修改订单详情的输出参数是({})]", i);
            return CommonResult.success("修改订单详情状态成功");
        } else {
            logger.info("[修改订单详情的输出参数是({})]", i);
            return CommonResult.failed("修改订单详情状态失败");
        }
    }

    @Override
    @GetMapping("/findOrderDetails")
    public CommonResult<?> findOrderDetails(OrderDetailsQuery orderDetailsQuery) {
        logger.info("[修改订单详情的输入参数是({})]", orderDetailsQuery);
        List<OrderDetails> orderList = orderMapper.findOrderDetails(orderDetailsQuery);
        logger.info("[修改订单详情的输出参数是({})]", orderList);
        return CommonResult.success(orderList, "查询订单详情信息成功");
    }

    @Override
    @GetMapping("/pay")
    public String pay(AliPayDTO aliPayDTO) {
        logger.info("[下单接口的详情的输入参数是({})]", aliPayDTO);
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(aliPayDTO.getSubject(), aliPayDTO.getTraceNo(), aliPayDTO.getTotalAmount(), "");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        logger.info("[下单接口的详情的输出参数是({})]", response.getBody());
        return response.getBody();
    }


    @Override
    @PostMapping("/pay/notify")
    public CommonResult<?> payNotify(HttpServletRequest request) throws Exception {
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");

            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                logger.info("[交易名称({})]", params.get("subject"));
                logger.info("[交易状态({})]", params.get("trade_status"));
                logger.info("[支付宝交易凭证号({})]", params.get("trade_no"));
                logger.info("[商户订单号({})]", params.get("out_trade_no"));
                logger.info("[交易金额({})]", params.get("total_amount"));
                logger.info("[买家在支付宝唯一id({})]", params.get("buyer_id"));
                logger.info("[买家付款时间({})]", params.get("gmt_payment"));
                logger.info("[买家付款金额({})]", params.get("buyer_pay_amount"));
//                System.out.println("交易名称: " + params.get("subject"));
//                System.out.println("交易状态: " + params.get("trade_status"));
//                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
//                System.out.println("商户订单号: " + params.get("out_trade_no"));
//                System.out.println("交易金额: " + params.get("total_amount"));
//                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
//                System.out.println("买家付款时间: " + params.get("gmt_payment"));
//                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单为已支付
                orderMapper.updateOrderState(tradeNo, 1, gmtPayment);
                orderMapper.updateOrderDetailsState(tradeNo, 1, gmtPayment);
            }
            return CommonResult.success("支付成功");
        } else {
            return CommonResult.failed("支付失败");

        }
    }

}
